<template>
  <div
    class="userinfo"
    style="display: flex; align-items: center; background-color: lightcyan"
  >
    <el-avatar v-for="item in user_data" :key="item.id" :src="item.avatar" />
    <div class="custom-descriptions margin-top">
      <div
        v-for="item in user_data"
        :key="item.id"
        class="custom-descriptions-item"
      >
        <div class="custom-label">昵称：</div>
        <div class="custom-content">{{ item.nick_name || "未填写" }}</div>
      </div>

      <div
        v-for="item in user_data"
        :key="item.id"
        class="custom-descriptions-item"
      >
        <div class="custom-label">签名：</div>
        <div class="custom-content">
          {{ item.signature || "这个人很懒，什么都没有留下" }}
        </div>
      </div>
    </div>
    <el-button type="primary" @click="openDialog2" round>详细信息 ></el-button>
  </div>
  <el-dialog v-model="dialogVisible2" title="详细个人信息" width="90%">
    <div
      style="display: flex; justify-content: space-between; align-items: center"
    >
      <el-avatar v-for="item in user_data" :key="item.id" :src="item.avatar" />
      <div>
        个人信息完成度：{{ calculateFilledFields() }}%
        <el-button type="success" @click="openDialog" round
          >修改个人信息</el-button
        >
      </div>
    </div>
    <el-dialog v-model="dialogVisible" title="修改个人信息" width="30%">
      <el-form v-for="temp in user_data" :key="temp.id" :model="temp">
        <el-form-item label="头像" :label-width="formLabelWidth">
          <div class="picture">
            <label for="fileInput" class="picture-label">
              <!-- 使用label元素来触发文件选择 -->
              <input
                type="file"
                id="fileInput"
                @change="handleFileInput"
                class="avatar-input"
              />
              <img v-if="editUrl" :src="editUrl" class="avatar" />
            </label>
          </div>
          <!-- </el-upload> -->
        </el-form-item>
        <el-form-item label="昵称" :label-width="formLabelWidth">
          <el-input v-model="editnick_name" autocomplete="off" />
        </el-form-item>
        <el-form-item label="姓名" :label-width="formLabelWidth">
          <el-input v-model="editname" autocomplete="off" />
        </el-form-item>
        <el-form-item label="年龄" :label-width="formLabelWidth">
          <el-input v-model="editage" autocomplete="off" />
        </el-form-item>
        <el-form-item label="性别" :label-width="formLabelWidth">
          <el-select v-model="editgender" placeholder="请选择">
            <el-option label="男" value="男" />
            <el-option label="女" value="女" />
          </el-select>
        </el-form-item>
        <el-form-item label="身份证" :label-width="formLabelWidth">
          <el-input v-model="editid_card" autocomplete="off" />
        </el-form-item>
        <el-form-item label="电话" :label-width="formLabelWidth">
          <el-input v-model="editphone" autocomplete="off" />
        </el-form-item>

        <el-form-item label="常居城市:">
          <el-cascader
            :props="props"
            v-model="area"
            placeholder="请选择省市区"
          />
        </el-form-item>
        <el-form-item label="职业:">
          <el-input v-model="career" autocomplete="off" />
        </el-form-item>
        <el-form-item label="您擅长于：">
          <el-checkbox-group v-model="type">
            <el-checkbox label="带宠" name="type" />
            <el-checkbox label="带娃" name="type" />
            <el-checkbox label="收纳" name="type" />
            <el-checkbox label="陪诊" name="type" />
            <el-checkbox label="跑腿" name="type" />
            <el-checkbox label="其他" name="type" />
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="理想时薪:">
          <el-col :span="9">
            <el-input
              v-model="lowest_wage"
              placeholder="最低"
              autocomplete="off"
            ></el-input>
          </el-col>
          <el-col :span="1" class="text-center">- </el-col>
          <el-col :span="9">
            <el-input
              v-model="highest_wage"
              placeholder="最高"
              autocomplete="off"
            ></el-input>
          </el-col>
        </el-form-item>
        <el-form-item label="您的简介:">
          <el-input v-model="profile" type="textarea" autocomplete="off" />
        </el-form-item>
        <el-form-item label="个性签名:">
          <el-input
            clearable="true"
            v-model="editsignature"
            type="textarea"
            autocomplete="off"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmDialog">确认</el-button>
        </span>
      </template>
    </el-dialog>
    <el-descriptions class="margin-top" :column="2" :size="size" border>
      <el-descriptions-item v-for="item in user_data" :key="item.id">
        <template #label> 昵称 </template>
        {{ item.nick_name || "未填写" }}
      </el-descriptions-item>
      <el-descriptions-item v-for="item in user_data" :key="item.id">
        <template #label> ID </template>
        {{ item.id || "未填写" }}
      </el-descriptions-item>
      <el-descriptions-item v-for="item in user_data" :key="item.id">
        <template #label> 姓名 </template>
        {{ item.name || "未填写" }}
      </el-descriptions-item>
      <el-descriptions-item v-for="item in user_data" :key="item.id">
        <template #label> 年龄 </template>
        {{ item.age || "未填写" }}
      </el-descriptions-item>

      <el-descriptions-item v-for="item in user_data" :key="item.id">
        <template #label> 性别 </template>
        {{ item.gender || "未填写" }}
      </el-descriptions-item>
      <el-descriptions-item v-for="item in user_data" :key="item.id">
        <template #label> 职业 </template>
        {{ item.career || "未填写" }}
      </el-descriptions-item>
      <el-descriptions-item v-for="item in user_data" :key="item.id">
        <template #label> 身份证 </template>
        {{ item.id_card || "未填写" }}
      </el-descriptions-item>
      <el-descriptions-item v-for="item in user_data" :key="item.id">
        <template #label> 电话 </template>
        {{ item.phone || "未填写" }}
      </el-descriptions-item>

      <!-- <el-descriptions-item v-for=" item  in  user_data " :key="item.id">
                <template #label>
                    地区
                </template>
                {{ item.area || "未填写" }}
            </el-descriptions-item> -->
      <el-descriptions-item v-for="item in user_data" :key="item.id">
        <template #label> 常居城市 </template>
        <div>
          <span v-if="item.area && item.area.length > 0">
            {{ item.area.join(" ") }}
          </span>
          <span v-else> 未填写 </span>
        </div>
      </el-descriptions-item>
      <el-descriptions-item v-for="item in user_data" :key="item.id">
        <template #label> 擅长于 </template>
        <div>
          <span v-if="item.type && item.type.length > 0">
            {{ item.type.join(" ") }}
          </span>
          <span v-else> 未填写 </span>
        </div>
      </el-descriptions-item>
      <el-descriptions-item v-for="item in user_data" :key="item.id">
        <template #label> 理想时薪 </template>
        <div>
          <span v-if="item.lowest_wage !== '' && item.highest_wage !== ''">
            {{ item.lowest_wage + "-" + item.highest_wage }}
          </span>
          <span v-else> 未填写 </span>
        </div>
      </el-descriptions-item>
      <el-descriptions-item v-for="item in user_data" :key="item.id">
        <template #label> 简介 </template>
        {{ item.profile || "未填写" }}
      </el-descriptions-item>
      <el-descriptions-item v-for="item in user_data" :key="item.id">
        <template #label> 个性签名 </template>
        {{ item.editsignature || "未填写" }}
      </el-descriptions-item>
    </el-descriptions>
  </el-dialog>
</template>

<script>
import { ref } from "vue";
import { ElNotification } from "element-plus";

export default {
  setup() {
    const dialogVisible = ref(false);

    const openDialog = () => {
      dialogVisible.value = true;
    };
    const dialogVisible2 = ref(false);

    const openDialog2 = () => {
      dialogVisible2.value = true;
    };

    return {
      dialogVisible,
      dialogVisible2,
      openDialog,
      openDialog2,
    };
  },
  data() {
    return {
      user_data: [],
      editname: "",
      editnick_name: "",
      editage: "",
      editgender: "",
      editid_card: "",
      editphone: "",

      editsignature: "",
      editUrl: "",
      career: "",
      type: [],
      lowest_wage: "",
      highest_wage: "",
      profile: "",
      province: [],
      city: [],
      district: [],
      // options: [
      // {
      //     value: 'province1',
      //     label: '省份1',
      //     children: [
      //         {
      //             value: 'city1',
      //             label: '城市1',
      //             children: [
      //                 {
      //                     value: 'district1',
      //                     label: '区域1'
      //                 },
      //             ]
      //         },
      //     ]
      // },
      // ],
      area: [],
      props: {
        lazy: true,
        lazyLoad: (node, resolve) => {
          const { level, value } = node;
          const nodes = [];
          if (level === 0) {
            this.axios
              .post("http://127.0.0.1:8000/get_provinces/")
              .then((res) => {
                if (res.data.success) {
                  res.data.provinces.map((province) => {
                    let obj = {
                      value: province,
                      label: province,
                      leaf: false,
                    };
                    nodes.push(obj);
                  });
                } else {
                  ElNotification({
                    title: "获取省份信息失败",
                    type: "error",
                  });
                }
                resolve(nodes);
              });
          } else if (level === 1) {
            const selectedProvince = value;
            // console.log(selectedProvince);
            const params = new URLSearchParams();
            params.append("province", selectedProvince);
            this.axios
              .post("http://127.0.0.1:8000/get_cities/", params)
              .then((res) => {
                if (res.data.success) {
                  res.data.cities.map((city) => {
                    let obj = {
                      value: city,
                      label: city,
                      leaf: false,
                    };
                    nodes.push(obj);
                  });
                }
                resolve(nodes);
              });
          } else {
            const selectedCity = value;
            const params = new URLSearchParams();
            params.append("city", selectedCity);
            this.axios
              .post("http://127.0.0.1:8000/get_districts/", params)
              .then((res) => {
                if (res.data.success) {
                  res.data.districts.map((district) => {
                    let obj = {
                      value: district,
                      label: district,
                      leaf: true,
                    };
                    nodes.push(obj);
                  });
                }
                resolve(nodes);
              });
          }
        },
      },
    };
  },
  methods: {
    handleFileInput(event) {
      const file = event.target.files[0];
      if (file) {
        const reader = new FileReader();
        reader.onload = () => {
          this.editUrl = reader.result;
        };
        reader.readAsDataURL(file);
      }
    },
    testRequst() {
      this.axios.post("http://127.0.0.1:8000/userInfo/").then((res) => {
        if (res.data.success) {
          // console.log(res.data);
          this.user_data = res.data.data;
          for (let item of this.user_data) {
            this.editname = item.name;
            this.editnick_name = item.nick_name;
            this.editage = item.age;
            this.editgender = item.gender;
            this.editid_card = item.id_card;
            this.editphone = item.phone;
            this.area = item.area !== null ? item.area : [];
            this.editsignature = item.signature;
            this.career = item.career;
            this.type = item.type !== null ? item.type : [];
            this.editUrl = item.avatar;
            this.lowest_wage = item.lowest_wage;
            this.highest_wage = item.highest_wage;
            this.profile = item.profile;
          }
        } else {
          ElNotification({
            title: res.data.title,
            message: res.data.message,
            type: "error",
          });
        }
      });
    },
    updateUserInfo() {
      // 构建需要发送到后端的数据对象
      const dataArray = Array.from(this.user_data);
      // 发送 POST 请求
      this.axios
        .post("http://127.0.0.1:8000/updateuser/", JSON.stringify(dataArray))
        .then((res) => {
          if (res.data.success) {
            // console.log("数据更新成功");
            // console.log(dataArray);
            ElNotification({
              title: "操作成功",
              message: "更新个人信息成功",
              type: "success",
            });
          } else {
            ElNotification({
              title: res.data.title,
              message: res.data.message,
              type: "error",
            });
          }
        });
    },
    confirmDialog() {
      this.dialogVisible = false;
      this.user_data.forEach((item) => {
        item.name = this.editname;
        item.nick_name = this.editnick_name;
        item.age = this.editage;
        item.gender = this.editgender;
        item.id_card = this.editid_card;
        item.phone = this.editphone;
        item.area = this.area;
        item.signature = this.editsignature;
        item.avatar = this.editUrl;
        item.career = this.career;
        item.type = this.type;
        item.lowest_wage = this.lowest_wage;
        item.highest_wage = this.highest_wage;
        item.profile = this.profile;
      });
      this.updateUserInfo();
    },
    calculateFilledFields() {
      const fields = [
        this.editname,
        this.editnick_name,
        this.editage,
        this.editgender,
        this.editid_card,
        this.editphone,
        this.area,
        this.editsignature,
        this.editUrl,
        this.career,
        this.type,
        this.editUrl,
        this.lowest_wage,
        this.highest_wage,
        this.profile,
      ];
      const filledFieldsCount = fields.reduce((count, value) => {
        if (
          value !== null &&
          (Array.isArray(value) ? value.length > 0 : true)
        ) {
          return count + 1;
        }
        return count;
      }, 0);
      return parseFloat(((filledFieldsCount / fields.length) * 100).toFixed(2));
    },
  },
  mounted() {
    this.testRequst();
  },
};
</script>

<style scoped>
.dialog-footer button:first-child {
  margin-right: 10px;
}

.el-avatar {
  margin: 20px;
  width: 100px;
  height: 100px;
}

.el-button {
  margin: 30px;
}

.cell-item {
  display: flex;
  align-items: center;
}

.avatar {
  width: 150px;
  height: 150px;
  object-fit: cover;
  /* 保持图片比例并填充元素 */
}

.avatar-input {
  display: none;
}

.userinfo {
  background-image: url("/src/assets/banner.jpg");
  background-size: cover;
}

.picture {
  border: 2px dashed #ccc;
  border-radius: 6px;
  padding: 5px;
  line-height: 0;
}

.custom-descriptions {
  display: flex;
  flex-direction: column;
}

.custom-descriptions-item {
  display: flex;
  margin-bottom: 10px;
}

.custom-label {
  font-weight: 700;
  margin-right: 8px;
  color: var(--el-text-color-regular);
}

.custom-content {
  font-weight: 400;
  color: var(--el-text-color-primary);
}
</style>
